import os
path = os.path
from importlib import import_module, util
from datetime import datetime
import zipfile
import requests

sn = import_module("switch_network")
printer = import_module("printer").IndentPrinter(indent=1)
auth_info = None
data_path = os.environ["DATA_PATH"]

# "yth000001": 开通任务满足度清单,
# "yth000002": 开通类指标清单,
# "yth000003": 开通在途类指标清单,
# "yth000004": 投诉类指标清单,
# "yth000005": 投诉在途类指标清单,
# "yth000006": 广义投诉指标清单,
# "yth000007": 10080升级投诉清单,
# "yth000008": 工信部升级投诉清单,
# "yth000009": 信访局升级投诉清单,
report_list = [
    # (
    #     "开通类指标清单",
    #     "yth000002",
    #     path.join(data_path, r"开通类指标\源数据\开通类指标清单.zip"),
    #     path.join(data_path, r"开通类指标\源数据\开通类指标清单.csv"),
    # ),
    (
        "投诉类指标清单",
        "yth000004",
        path.join(data_path, r"投诉类指标\源数据\投诉类指标清单.zip"),
        path.join(data_path, r"投诉类指标\源数据\投诉类指标清单.csv"),
    ),
]


def generate_files(name, reportId):
    printer(f"[生成文件] {name}:{reportId} 开始")
    try:
        url = "http://10.243.24.152:8080/gdjk-api/ui/v1/nhm/kpi/common/force-rebuild"
        cur_month = datetime.now().strftime("%Y%m")
        printer("[生成文件] 当前月份：", cur_month)

        printer(f"[生成文件] {name},请求发起")
        printer(f"[生成文件] {name},正在生成文件，请耐心等待...")

        params = {
            "timeType": "month",
            "endTime": cur_month,
            "customerType": "3",
            "city": "26",
            "reportId": reportId,
        }

        response = requests.get(
            url,
            params=params,
            headers=auth_info["headers"],
            cookies=auth_info["cookies"],
        )
        if response.status_code == 200:
            try:
                data = response.json()
                return data["data"]
            except ValueError:
                printer("Response Content:", response.text)
                raise ValueError("无法解析 JSON 数据")
        else:
            printer(f"Request failed with status code {response.status_code}")
            printer("Response Content:", response.text)
            raise ValueError(f"生成文件{name}请求失败")
    except Exception as e:
        printer(f"[生成文件] {name}失败，发生错误：", e)
        raise e


def download_files(name, file_id, local_zip_path, local_csv_path):
    try:
        printer(f"[下载文件] {name} file_id：", file_id)
        url = f"http://10.243.24.152:8080/gdjk-api/ui/v1/sys/file/download?id={file_id}"

        if os.path.exists(local_zip_path):
            printer(f"[下载文件] {name} ZIP 文件已存在，删除旧文件：{local_zip_path}")
            os.remove(local_zip_path)
        if os.path.exists(local_csv_path):
            printer(f"[下载文件] {name} CSV 文件已存在，删除旧文件：{local_csv_path}")
            os.remove(local_csv_path)

        printer(f"[下载文件]  {name}请求发起：{url}")
        response = requests.get(
            url, headers=auth_info["headers"], cookies=auth_info["cookies"], stream=True
        )

        if response.status_code == 200:
            try:
                with open(local_zip_path, "wb") as file:
                    for chunk in response.iter_content(chunk_size=8192):
                        file.write(chunk)
                printer(f"[下载文件]  {name} 下载完成，文件已保存到：{local_zip_path}")

                printer(f"[下载文件]  {name} 开始解压 ZIP 文件：{local_zip_path}")
                with zipfile.ZipFile(local_zip_path, "r") as zip_ref:
                    zip_contents = zip_ref.namelist()
                    if len(zip_contents) != 1:
                        raise ValueError(
                            f"{name}ZIP 文件内容异常，应仅包含一个 CSV 文件。"
                        )

                    csv_file_in_zip = zip_contents[0]
                    if not csv_file_in_zip.endswith(".csv"):
                        raise ValueError(f"{name} ZIP 文件中的文件不是 CSV 格式。")

                    # 解压到目标路径
                    zip_ref.extract(csv_file_in_zip, os.path.dirname(local_csv_path))
                    extracted_csv_path = os.path.join(
                        os.path.dirname(local_csv_path), csv_file_in_zip
                    )

                    os.rename(extracted_csv_path, local_csv_path)
                    printer(
                        f"[下载文件] {name}解压完成，CSV 文件已保存到：{local_csv_path}"
                    )

                printer(f"[下载文件] {name} 删除原始 ZIP 文件：{local_zip_path}")
                os.remove(local_zip_path)

            except Exception as e:
                printer(f"[下载文件] {name} 失败，发生错误：{e}")
                raise e
        else:
            printer(f"[下载文件] {name} 请求失败，状态码：{response.status_code}")
            printer("Response Content:", response.text)
            raise ValueError("下载文件请求失败")
    except Exception as e:
        printer("[下载文件] 失败，发生错误：", e)
        raise e


def main():
    global auth_info

    # sn.connect_to_internal()
    if sn.wait_for_system("10.243.24.152", "8080"):
        print("家集客系统已可用")
        printer("[下载数据] 开始")
        printer.add(1)
        auth_info = import_module("login_jjk").main()
        for name, reportId, local_zip_path, local_csv_path in report_list:
            file_id = generate_files(name, reportId)
            download_files(name, file_id, local_zip_path, local_csv_path)
        printer("[下载数据] 👏 完成，总耗时<run_time>。", run_time="hh:mm:ss")

        # sn.connect_to_internet()


if __name__ == "__main__":
    main()
